#!/usr/bin/python3
# -*- coding: utf-8 -*-

# Apache License
# Version 2.0, January 2004
# http://www.apache.org/licenses/


# Author: Yuwenhai <y.wh@foxmail.com>
# Date:   2022-04-19
# Page:   www.whlws.cn
# Gitee:  https://gitee.com/yuwenhai/

#本工具可以将sensor fae提供的寄存器配置转换成Sensor.xml的格式
#使用正则表达式自动提取参数，十分稳定便捷，欢迎测试并提出意见

import sys
import os
import re


############################自定义配置开始##############################
#输入原始寄存器配置文件
#如果是excel，需要提取出文本的形式
IN = "~/LINUX/android/vendor/qcom/proprietary/chi-cdk/vendor/sensor/default/imx335/A.txt"

#sensor.xml中定义的regAddrType值
#   0x3000 值为2
#   0x30   值为1
regAddrType = 2

#sensor.xml中定义的regDataType值
#   0x0000 值为2
#   0x00   值为1
regDataType = 1

#翻转寄存器地址和值的顺序
#输入文件的每一行中：
#   前面是寄存器地址，后面是值。设置为False
#   前面是值，后面是寄存器地址。设置为True
toggleKeyValue = False

############################自定义配置结束##############################


#regSetting中配置的xml字段模板
#此处也可以换成c语言的模板。
regSettingCommentTemp = \
    '''

<!-- %s -->
<regSetting>
  <registerAddr>0x%s</registerAddr>
  <registerData>0x%s</registerData>
  <regAddrType range="[1,4]">%d</regAddrType>
  <regDataType range="[1,4]">%d</regDataType>
  <operation>WRITE</operation>
  <delayUs>0x0</delayUs>
</regSetting>'''

regSettingTemp = \
    '''
<regSetting>
  <registerAddr>0x%s</registerAddr>
  <registerData>0x%s</registerData>
  <regAddrType range="[1,4]">%d</regAddrType>
  <regDataType range="[1,4]">%d</regDataType>
  <operation>WRITE</operation>
  <delayUs>0x0</delayUs>
</regSetting>'''


def regSettingSet(addr, value, comment=""):
    '''
    对模板进行预处理,配置地址类型,值类型,sleep时间等字段,
    只返回完整的字段
    '''

    if toggleKeyValue:
        tmp = addr
        addr = value
        value = tmp

    # print([addr, value, comment])

    if comment != "":
        return regSettingCommentTemp % (comment, addr, value, regAddrType, regDataType)
    else:
        return regSettingTemp % (addr, value, regAddrType, regDataType)


def getHexNum(inputstr):
    '''
    使用正则表达式提取16进制数字,限制长度为2到4位数字
    '''
    return re.findall('[0-9a-fA-F]{2,4}', inputstr)

def checkAndRecord(hexData):
    '''
    校验Addr和Val是否正确
    '''
    if len(hexData) <= 1:
        return False
    try:
        addr = int(hexData[0],16)
        val = int(hexData[1],16)
    except:
        return False
    return True

def dump2file(fd,record):
    fout = open(fd, 'w+')


def main():
    global regAddrType
    global regDataType
    if len(sys.argv) > 1:
        fin = os.path.realpath(sys.argv[1])
    else:
        fin = os.path.realpath(IN)

    if not os.path.exists(fin):
        print("输入文件不存在:[%s]\n请检查输入参数 或 脚本的预设值" % fin)
        exit(0)
    else:
        print("使用的配置文件:[%s]" % fin)
        print("输出至:[%s.out]" % fin)

    fout = open("%s.out" % fin, 'w+')
    with open(fin) as fd:
        lines = fd.readlines()
        for line in lines:
            line = line.replace("\n", "").replace(
                "\r", "").replace("0x", "").replace("0X", "")
            comment = ''

            if len(re.findall('^[ \t]*//.*', line)) or len(re.findall('^[ \t]*#.*', line)):
                continue

            commentline = re.findall('//[ \t]*(.*)', line)
            if len(commentline) > 0:
                comment = ''.join(commentline)
                line = line.replace(comment, '')

            hexData = getHexNum(line)
            
            if checkAndRecord(hexData) == False:
                continue
            
            if len(hexData[0]) == 2:
                regAddrType = 1
            elif len(hexData[0]) == 4:
                regAddrType = 2
            else:
                continue
            if len(hexData[1]) == 2:
                regDataType = 1
            elif len(hexData[1]) == 4:
                regDataType = 2
            else:
                continue
            fout.write(regSettingSet(hexData[0], hexData[1], comment))
    fout.close()


if __name__ == "__main__":
    main()
